package com.atguigu.flink.state.keyedstate;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2023/11/17

 示例:检测每种传感器的水位值，如果连续的两个水位值超过10，就输出报警。
 */
public class Demo1_ValueState
{
    public static void main(String[] args) {
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

                env
                   .socketTextStream("hadoop102", 8888)
                   .map(new WaterSensorMapFunction())
                   //按照id分组
                    .keyBy(WaterSensor::getId)
                    .process(new KeyedProcessFunction<String, WaterSensor, String>()
                    {
                        //在Task被创建后，从备份中恢复
                        @Override
                        public void open(Configuration parameters) throws Exception {
                            lastVc = getRuntimeContext().getState(new ValueStateDescriptor<>("lastVc", Integer.class));
                        }

                        //声明状态
                        private ValueState<Integer> lastVc;
                        @Override
                        public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                            System.err.println(value);
                            //取出状态中存储的值。第一次操作，状态中没有存储值，此时获取的是null
                            Integer lastVcNum = lastVc.value();

                            if (lastVcNum != null && value.getVc() > 10 && lastVcNum > 10){
                                out.collect(ctx.getCurrentKey() +" 连续两个传感器的水位分别是:"+lastVcNum + ","+value.getVc() +" 超过10");
                            }

                            //记录当前水位
                            lastVc.update(value.getVc());

                        }
                    })
                    .print();
        
                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
        
    }
}
